﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace YArchitech.Temp
{
	internal class HYPipeSystemTree : TreeView
	{
		public HYPipeSystem HYPipeSystem
		{
			get
			{
				return this.m_HYPipeSystem;
			}
		}

		public TreeNode FindTreeNode(HYMEPObject comp)
		{
			TreeNode result = null;
			this.m_dicObjToNode.TryGetValue(comp, out result);
			return result;
		}

		public HYPipeStraight GetComponent(TreeNode tn)
		{
			if (tn.Tag == null)
			{
				return null;
			}
			return tn.Tag as HYPipeStraight;
		}

		public bool SelectComponent(HYMEPObject comp)
		{
			base.CollapseAll();
			TreeNode treeNode = this.FindTreeNode(comp);
			treeNode.Expand();
			base.SelectedNode = treeNode;
			return true;
		}

		public bool Attach(HYPipeSystem system)
		{
			base.Nodes.Clear();
			if (system == null)
			{
				return false;
			}
			this.m_HYPipeSystem = system;
			if (this.m_dicObjToNode != null)
			{
				this.m_dicObjToNode.Clear();
			}
			else
			{
				this.m_dicObjToNode = new Dictionary<HYMEPObject, TreeNode>();
			}
			this.AddObject(null, this.m_HYPipeSystem.Root);
			if (base.Nodes.Count == 0)
			{
				return false;
			}
			base.ExpandAll();
			base.Update();
			return true;
		}

		private void AddObject(TreeNode ndParent, HYMEPObject mepObj)
		{
			if (mepObj == null)
			{
				return;
			}
			if (mepObj is HYPipeStraight)
			{
				HYPipeStraight mepObject = mepObj as HYPipeStraight;
				TreeNode treeNode = new TreeNode();
				this.Binding(treeNode, mepObject);
				if (ndParent == null)
				{
					base.Nodes.Add(treeNode);
				}
				else
				{
					ndParent.Nodes.Add(treeNode);
				}
				this.AddObject(treeNode, mepObj.Next);
				return;
			}
			if (mepObj is HYPipeTee)
			{
				this.AddObject(ndParent, mepObj.Next);
				HYPipeTee hypipeTee = mepObj as HYPipeTee;
				this.AddObject(ndParent, hypipeTee.Side);
				if (mepObj is HYPipeCross)
				{
					HYPipeCross hypipeCross = mepObj as HYPipeCross;
					this.AddObject(ndParent, hypipeCross.Side2);
					return;
				}
			}
			else if (!(mepObj is HYPipeTerminal))
			{
				this.AddObject(ndParent, mepObj.Next);
			}
		}

		private void Binding(TreeNode nd, HYPipeStraight mepObject)
		{
			nd.Text = mepObject.ShowString;
			nd.Tag = mepObject;
			this.m_dicObjToNode.Add(mepObject, nd);
		}

		private Dictionary<HYMEPObject, TreeNode> m_dicObjToNode;

		private HYPipeSystem m_HYPipeSystem;
	}
}
